//
//  BQWelfare_BannerViewController.m
//  Adorable_Things
//
//  Created by ybq on 16/1/15.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "BQWelfare_BannerViewController.h"
#import "BQNavViewCommon.h"
#import "BQWelfareCollectionViewFirstCell.h"
#import "BQWelfareCollectionViewNormalCell.h"
#import "BQwelfareCollectionReusableView.h"
#import "BQAdsModel.h"
#import "BQWelfareListModel.h"
#import "BQHtmlViewController.h"
#import "BQWelfareViewController.h"

@interface BQWelfare_BannerViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) BQNavViewCommon *navView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) BQAdsModel *headerModel;
@property (nonatomic, assign) NSInteger page;

@end

@implementation BQWelfare_BannerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"LaunchImage-568h"]];
    _dataArray = [NSMutableArray array];
    // Do any additional setup after loading the view.
    [self createUI];
    [self requestData];
}

- (void)createUI {
    _navView = [[BQNavViewCommon alloc] initWithFrame:CGRectMake(0, 20, kWidth, 44)];
    [_navView.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    _navView.titleLabel.text = @"福利社";
    [self.view addSubview:_navView];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 15;
    flowLayout.itemSize = CGSizeMake((kWidth - 45) / 2, kWidth / 1.63);
    flowLayout.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
    flowLayout.headerReferenceSize = CGSizeMake(kWidth, kWidth / 2.27);
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, kWidth, kHeight - 64) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 0;
        [self requestData];
    }];
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page += 1;
        [self requestData];
    }];
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[BQwelfareCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"BQwelfareCollectionReusableView"];
    [_collectionView registerNib:[UINib nibWithNibName:@"BQWelfareCollectionViewFirstCell" bundle:nil] forCellWithReuseIdentifier:@"BQWelfareCollectionViewFirstCell"];
    [_collectionView registerNib:[UINib nibWithNibName:@"BQWelfareCollectionViewNormalCell" bundle:nil] forCellWithReuseIdentifier:@"BQWelfareCollectionViewNormalCell"];
}

- (void)requestData {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // headerView
    [manager POST:@"http://api.menghuoapp.com/v1/welfare_banner/at_home" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *dataArray = responseObject[@"data"];
        _headerModel = [[BQAdsModel alloc] init];
        [_headerModel setValuesForKeysWithDictionary:dataArray.firstObject];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    // collectionViewItem
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"page"] = [NSString stringWithFormat:@"%ld",(long)_page];
    parameters[@"page_size"] = @"20";
    [manager POST:@"http://api.menghuoapp.com/v1/welfare_good/list" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *dataArray = responseObject[@"data"];
        if (_page == 0) {
            [_dataArray removeAllObjects];
        }
        for (NSDictionary *dic in dataArray) {
            BQWelfareListModel *model = [[BQWelfareListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_dataArray addObject:model];
        }
        [_collectionView reloadData];
        [_collectionView.mj_footer endRefreshingWithNoMoreData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    [_collectionView.mj_header endRefreshing];
}

- (void)backButtonAction:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark collectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BQWelfareCollectionViewFirstCell *firstCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BQWelfareCollectionViewFirstCell" forIndexPath:indexPath];
    BQWelfareCollectionViewNormalCell *normalCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BQWelfareCollectionViewNormalCell" forIndexPath:indexPath];
    BQWelfareListModel *model = _dataArray[indexPath.row];
    normalCell.model = model;
    firstCell.model = model;
    if (indexPath.row == 0) {
        return firstCell;
    }
    return normalCell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return CGSizeMake(kWidth - 30, 130);
    }
    return CGSizeMake((kWidth - 45) / 2, kWidth / 1.63);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isKindOfClass:[UICollectionElementKindSectionHeader class]]) {
        BQwelfareCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"BQwelfareCollectionReusableView" forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor whiteColor];
        headerView.model = _headerModel;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [headerView addGestureRecognizer:tap];
        return headerView;
    } else {
        return nil;
    }
}

- (void)tapAction:(UITapGestureRecognizer *)tap {
    BQHtmlViewController *htmlVC = [[BQHtmlViewController alloc] init];
    htmlVC.myTitle = @"惊喜联盟兑奖";
    htmlVC.urlStr = @"http://m.menghuoapp.com/act/tddj/index.html";
    [self.navigationController pushViewController:htmlVC animated:YES];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    BQWelfareViewController *welfareVC = [[BQWelfareViewController alloc] init];
    BQWelfareListModel *model = _dataArray[indexPath.row];
    welfareVC.good_id = model.good_id;
    [self.navigationController pushViewController:welfareVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
